﻿using RSALicCore;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace RSALicUI
{
    public partial class AuthForm : FormBase
    {
        public AuthForm()
        {
            InitializeComponent();

            keyCtrl.QrDetected += KeyCtrl_KeyDetected;
            keyCtrl.Title = "输入授权二维码";
        }

        private void KeyCtrl_KeyDetected(string obj)
        {
            if (obj.Contains("Test Data"))
            {
                return;
            }
            if (loaded)
            {
                if (string.IsNullOrEmpty(obj))
                {
                    labelKey.Text =
                    "未识别到有效的授权！" + CommResources.QrTips;
                }
                else
                {
                    if (LicVertifyer.Vertify(CommResources.PubKey, obj))
                    {
                        MessageBox.Show("恭喜您，授权通过！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        LicManager.Save(obj);
                        this.DialogResult = DialogResult.OK;
                    }
                    else
                    {
                        MessageBox.Show("对不起，授权未通过！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
        }

        bool loaded = false;
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            labelData.Text = $"请将左侧的 本机注册码 提供给【{CommResources.Company}】获取 授权二维码";

            labelKey.Text = $"请双击右侧的二维码区域，将【{CommResources.Company}】提供的 授权二维码 导入进行认证";

            loaded = true;
        }

        protected override void OnShown(EventArgs e)
        {
            base.OnShown(e);

            if (!string.IsNullOrEmpty(CommResources.Website))
            {
                linkLabel1.Text = CommResources.Website;
                linkLabel1.LinkClicked += LinkLabel1_LinkClicked;
            }
            else
            {
                linkLabel1.Visible = false;
            }
        }

        private void LinkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            System.Diagnostics.Process.Start("www.baidu.com");
        }

        /// <summary>
        /// 校验或者请求授权
        /// </summary>
        /// <returns></returns>
        public static bool VertifyLic()
        {
            var lic = LicManager.Read();
            if (!string.IsNullOrEmpty(lic))
            {
                if (LicVertifyer.Vertify(CommResources.PubKey, lic))
                {
                    return true;
                }
            }

            var af = new AuthForm();
            if (af.ShowDialog() == DialogResult.OK)
            {
                return true;
            }

            return false;
        }
    }
}
